package com.evil.application.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.evil.application.mapper.FavouriteApplicationMapper;
import com.evil.application.pojo.entity.FavouriteApplication;
import com.evil.application.service.FavouriteApplicationService;
import com.evil.common.account.util.LoginUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * 用户常用应用表
 *
 * @author liyang
 * @date 2022-08-08 00:00
 */
@Slf4j
@RestController
@AllArgsConstructor
public class FavouriteApplicationServiceImpl extends ServiceImpl<FavouriteApplicationMapper, FavouriteApplication> implements FavouriteApplicationService {

    private final LoginUtil loginUtil;

    private final ApplicationLogServiceImpl logService;

    @Override
    public int batchInsert(List<FavouriteApplication> list) {
        return baseMapper.batchInsert(list);
    }

    /**
     * 添加/移除常用
     *
     * @param applicationId applicationId
     */
    @Override
    public void favourite(Long applicationId, Integer favourite) {
        Long loginUserId = loginUtil.getLoginUserId();
        Long loginEnterpriseId = loginUtil.getLoginEnterpriseId();
        FavouriteApplication favouriteApplication = this.baseMapper.findUserApp(loginUserId, applicationId).orElseGet(() -> {
            FavouriteApplication newFavouriteApp = new FavouriteApplication();
            newFavouriteApp.setUserId(loginUserId);
            newFavouriteApp.setEnterpriseId(loginEnterpriseId);
            newFavouriteApp.setApplicationId(applicationId);
            return newFavouriteApp;
        });

        favouriteApplication.setFavourite(favourite);
        logService.saveAndCheck(this.baseMapper, FavouriteApplication::getFavouriteId, favouriteApplication);
    }
}

